<template>
  <el-card>
    <el-form
      ref="ruleFormRef"
      :model="form"
      status-icon
      :rules="rules"
      label-width="80px"
    >
      <el-col :span="24" style="margin: 0 0.5rem; display: flex; justify-content: space-between;">
        <el-form-item label="用户名">
          <el-input type="text" v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="text" v-model="form.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" prop="checkPass">
          <el-input type="email" v-model="form.email" autocomplete="off" />
        </el-form-item>
      </el-col>
      <el-col class="text-center" :span="24" style="margin: 0 0.5rem; display: flex;justify-content: end;">
       <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >查询</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
      </el-col>
    </el-form>
  </el-card>
  <el-card style="margin-top: 20px">
    <template #header>
      <div>
        <span>用户列表</span>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button class="button" size="small" @click="onAdd()" type="primary">
          注册用户
        </el-button>
      </div>
    </template>
    <div class="table-container">
      <el-table :data="state.list" stripe style="width: 100%">
        <el-table-column type="index" prop="" label="" width="50">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="password" label="密码"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="status" label="用户类型" width="150">
          <template #default="scope">
            <el-button
              size="small"
              plain
              type="primary"
              v-if="scope.row.status == '1'"
              @click="onEditStatus(scope.row.id)"
              >系统管理员</el-button
            >
            <el-button
              size="small"
              plain
              type="primary"
              v-if="scope.row.status == '0'"
              @click="onEditStatus(scope.row.id)"
              >普通账号</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" align="center" width="150">
          <template #default="scope">
            <el-button
              size="small"
              plain
              type="primary"
              @click="onEdit(scope.$index)"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--注册/修改用户对话框-->
    <el-dialog
      width="50%"
      v-model="state.dialog.show"
      :title="state.dialog.title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
      @close="onClose"
    >
      <!--使用el-form组件进行数据添加和修改-->
      <el-form
        ref="myform"
        :model="state.mymodel"
        label-width="150px"
        style="margin: 10px; width: auto"
      >
        <el-form-item label="姓名" required>
          <el-col :span="15">
            <el-form-item prop="userName">
              <el-input
                type="string"
                v-model="state.mymodel.username"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="登录密码" required>
          <el-col :span="15">
            <el-form-item prop="currentPassword">
              <el-input
                type="password"
                v-model="state.mymodel.password"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item prop="status" label="账号类型:">
          <!--使用label表示值-->
          <el-radio-group v-model="state.mymodel.status">
            <el-radio-button label="0">普通账号</el-radio-button>
            <el-radio-button label="1">系统管理员</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱:" required>
          <el-col :span="15">
            <el-input type="email" v-model="state.mymodel.email"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item class="text_right">
          <el-button type="primary" @click="onSave(myform)">保 存</el-button>
          <el-button @click="state.dialog.show = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-card>
</template>
<script setup>
//注意：vue3.x组合式api，需要在<script>里面使用setup

import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
//导入axios实例(从封装的http.js中导入)
import http from "../../util/http.js";
//使用一个reactive方法定义响应式对象
const state = reactive({
  //数据列表
  list: [],
  //与表单绑定
  mymodel: {
    username: "",
    password: "",
    email: "",
    status: "0",
  },

  //控制对话框
  dialog: {
    title: "",
    show: false,
    option: "",
  },
  item: {},
});
const ruleFormRef = ref();
// 获取用户列表
const getUserList = () => {
  http.get("/user/list").then((res) => {
    if (res.status === 200) {
      //更新表格
      state.list = res.data.data;
    }
  });
};
const form = ref({
  username: '',
  password: '',
  email: '',
});
//生命周期钩子
onMounted(() => {
  getUserList();
});
//响应注册按钮,打开注册对话框
const onAdd = () => {
  //弹出注册对话框
  state.dialog = {
    title: "用户注册",
    show: true,
    option: "add",
  };
};
//响应修改按钮,打开修改对话框
const onEdit = (index) => {
  //获得要修改用户的信息
  let user = state.list[index];
  //回填数据
  state.mymodel = {
    id: user.id,
    username: user.username,
    password: user.password,
    email: user.email,
    status: user.status,
  };
  //弹出注册对话框
  state.dialog = {
    title: "修改用户信息",
    show: true,
    option: "update",
  };
};
//响应注册对话框保存按钮
const myform = ref();
const onSave = async (form) => {
  if (state.dialog.option == "add") {
    //响应注册的保存动作
    let valid = await form.validate();
    if (valid) {
      let res = await http.post("/user/add", state.mymodel);
      if (res.data.code === 200) {
        // 操作成功
        ElMessage({
          message: res.data.message,
          type: "success",
        });
      } else {
        ElMessage({
          message: res.data.message,
          type: "error",
        });
        return;
      }
    }
  } else if (state.dialog.option == "update") {
    //响应修改的保存动作
    await form.validate(async (valid) => {
      if (valid) {
        let res = await http.put("/user/edit", state.mymodel);
        if (res.data.code === 200) {
          // 操作成功
          ElMessage({
            message: res.data.message,
            type: "success",
          });
        } else {
          ElMessage({
            message: res.data.message,
            type: "error",
          });
          return;
        }
      }
    });
  }
  getUserList();
  state.dialog = {
    title: "",
    show: false,
    option: "",
  };
};
const onClose = () => {
  state.mymodel = {
    id: "",
    username: "",
    password: "",
    email: "",
    status: "0",
  };
  myform.value.resetFields();
};

const onEditStatus = (id) => {
  console.log(id);
  http.get("/user/editStatus/" + id).then((res) => {
    console.log(res);
    if (res.data.code === 200) {
      ElMessage({
        message: res.data.message,
        type: "success",
      });
      getUserList();
    } else {
      ElMessage({
        message: res.data.message,
        type: "error",
      });
    }
  });
};
const submitForm = async (formEl) => {
  console.log(form.value);
  const res = await http.post('/user/list', form.value)
  if(res.data.code === 200) {
    state.list = res.data.data;
  }
};
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  getUserList();
  form.value = {}
};
</script>
<style scoped>
.table-container {
  text-align: right;
}
</style>
